<template>
	<view class="content">
		<!-- #ifdef APP-PLUS || H5 -->
		<view @click="echarts.onClick" :prop="optionData"  :moduleParamProp="moduleParam"  :change:moduleParamProp="echarts.moduleParamUp" :change:prop="echarts.updateEcharts" :id="moduleParam.id" class="echarts" ></view>
		<button @click="changeOption">更新数据</button>
		<!-- #endif -->
		<!-- #ifndef APP-PLUS || H5 -->
		<view>非 APP、H5 环境不支持</view>
		<!-- #endif -->
	</view>
</template>
<script>
	
	export default {
		data() {
			return {
				
			}
		},
		props:{
			moduleParam:{
				type:Object,
				default:()=>{
					id: "myCharts";
					width: "100%";
					height: "300rpx"
				}
			},
			optionData:{
				type:Object,
				default:()=>{}
			}
		},
		onLoad() {

		},
		methods: {
			changeOption() {
				// 父组件刷新数据
				this.$emit("changeOption")
			},
			onViewClick(options) {
				this.$emit("getClickData",options)
			}
		}
	}
</script>

<script module="echarts" lang="renderjs">
	import echartsConfig from '@/common/echarts-config.js'
	let myChart
	export default {
		data(){
			return{
				clickData:null
			}
		},
		mounted() {
			if (typeof window.echarts === 'function') {
				this.initEcharts()
			} else {
				// 动态引入较大类库避免影响页面展示
				const script = document.createElement('script')
				// view 层的页面运行在 www 根目录，其相对路径相对于 www 计算
				script.src = 'static/echarts.min.js'
				script.onload = this.initEcharts.bind(this)
				document.head.appendChild(script)
			}
		},
		methods: {
			initEcharts(){
				echarts.registerTheme('echartsConfig',echartsConfig )  //注册主题
				myChart = echarts.init(document.getElementById(this.moduleParam.id),"echartsConfig")
				// 观测更新的数据在 view 层可以直接访问到
				myChart.setOption(this.optionData)
				// 点击传参
				myChart.on('click', params => {
					console.log(params)
					this.clickData = params
				})
			},
			updateEcharts(newValue, oldValue, ownerInstance, instance) {
				// 监听 service 层数据变更
				console.log(newValue)
				myChart = echarts.init(document.getElementById(this.moduleParam.id),"echartsConfig")
				myChart.setOption(newValue)
			},
			moduleParamUp(newvalue,oldvalue){},
			onClick(event, ownerInstance) {
				console.log(this.clickData)
				ownerInstance.callMethod('onViewClick',{
					value:this.clickData.value,
					name:this.clickData.name,
					dataIndex:this.clickData.dataIndex,
					seriesName:this.clickData.seriesName
				})
			}
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.echarts {
		margin-top: 100px;
		width: 100%;
		height: 600rpx;
	}
</style>
